package control;

import redistool.RedisTool;
import swing.CommonTree;
import utils.PropertiesUtil;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @Title: 窗口鼠标响应处理类
 * @Package
 * @Description: 处理窗口的拖动
 * @author: GaleBlade
 * @date:
 */
public class MouseControl extends MouseAdapter {

	private RedisTool redisTool;
	private CommonTree tree;
	//创建菜单
	private JPopupMenu menu;

	/**
	 * 构造方法
	 */
	public MouseControl(RedisTool redisTool, CommonTree tree) {
		this.redisTool = redisTool;
		this.tree = tree;
		initMenu();
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		super.mouseClicked(e);
		int x = e.getX();
		int y = e.getY();
		int selRow = tree.getRowForLocation(e.getX(), e.getY());
		//检测鼠标右键并做动作
		if(e.getButton()==MouseEvent.BUTTON3 && selRow==0){
			//获取右键点击所在树节点路径
			TreePath pathForLocation = tree.getPathForLocation(x, y);
			tree.setSelectionPath(pathForLocation);
			//显示右键菜单
			menu.show(tree, x, y);
		}
	}

	/**
	 *
	 */
	@Override
	public void mouseEntered(MouseEvent e) {

	}

	/**
	 *
	 */
	@Override
	public void mouseExited(MouseEvent e) {

	}

	/**
	 *
	 */
	@Override
	public void mouseDragged(MouseEvent e) {

	}

	@Override
	public void mouseMoved(MouseEvent e) {

	}

	/**
	 * 鼠标双击树节点响应方法
	 */
	@Override
	public void mousePressed(MouseEvent e) {
		int selRow = tree.getRowForLocation(e.getX(), e.getY());
//		TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
		if(selRow == 0) {
			//展开redis节点
			if(e.getClickCount()%2 == 0) {
				tree.change();
				tree.expand();
			}
		}else {
			//展开db节点
			if(e.getClickCount()%2 == 0) {
				tree.changeSize();
				tree.expand();
			}
		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

	/**
	 * 初始化右键菜单
	 */
	private void initMenu(){
		menu = new JPopupMenu();
		//添加菜单选项
		JMenuItem menuItem=new JMenuItem("删除连接");
		menu.add(menuItem);
		//菜单项绑定监听
		menuItem.addActionListener(e -> {
			// TODO Auto-generated method stub
			//获取当前选择的节点
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
			//读取配置文件
			Map<String,String> cache = new HashMap<>();
			PropertiesUtil info = new PropertiesUtil("INFO.properties");
			List<String> keys = info.getAllKeys();
			for (String key : keys){
				cache.put(key, info.get(key));
			}
			//删除配置文件中对应的数据
			cache.remove(node.toString());
			info.update(cache,"INFO.properties");
			//删除面板上的tree
			redisTool.removeTree(node.toString());
		});
	}

}
